<?php

namespace App\Jobs;

use App\Models\Cart;
use App\Services\CartPriceService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class UpdateCartPricesJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected Cart $cart;

    /**
     * Create a new job instance.
     */
    public function __construct(Cart $cart)
    {
        $this->cart = $cart;
    }

    /**
     * Execute the job.
     */
    public function handle(CartPriceService $priceService): void
    {
        try {
            $priceChanges = $priceService->updateCartPrices($this->cart);
            
            if (!empty($priceChanges)) {
                Log::info('Cart prices updated', [
                    'cart_id' => $this->cart->id,
                    'user_id' => $this->cart->user_id,
                    'changes_count' => count($priceChanges),
                ]);
            }
        } catch (\Exception $e) {
            Log::error('Failed to update cart prices', [
                'cart_id' => $this->cart->id,
                'error' => $e->getMessage(),
            ]);
            
            throw $e;
        }
    }
}
